#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

# Usage:
# Run the service in the local environment:  ./scripts/run
# Run the service inside a Docker container: ./scripts/run -s
# Run the service inside a Docker container: ./scripts/run --in-sandbox
# Show how to use this script:               ./scripts/run -h
# Show how to use this script:               ./scripts/run --help

# Debug|Release
CONFIGURATION=Release

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )/"
source "$APP_HOME/scripts/.functions.sh"

# Folder where PCS sandboxes cache data. Reuse the same folder to speed up the
# sandbox and to save disk space.
# Use PCS_CACHE="$APP_HOME/.cache" to cache inside the project folder
PCS_CACHE="/tmp/azure/iotpcs/.cache"

help() {
    echo "Usage:"
    echo "  Run the service in the local environment:  ./scripts/run"
    echo "  Run the service inside a Docker container: ./scripts/run -s|--in-sandbox"
    echo "  Show how to use this script:               ./scripts/run -h|--help"
}

run() {
    check_dependency_dotnet

    cd $APP_HOME
    ./scripts/env-vars-check

    dotnet restore --verbosity=quiet

    echo "Starting Telemetry service..."
    dotnet run --configuration $CONFIGURATION --project WebService/*.csproj
}

setup_sandbox_cache() {
    mkdir -p $PCS_CACHE/sandbox/.config
    mkdir -p $PCS_CACHE/sandbox/.dotnet
    mkdir -p $PCS_CACHE/sandbox/.nuget
    echo "Note: caching build files in $PCS_CACHE"
}

run_in_sandbox() {

    setup_sandbox_cache

    cd $APP_HOME

    # In Windows this script should use docker.exe, in which case
    # the parameters syntax is different, e.g. volumes path
    # (i.e. C:\path\path\... vs /c/path/path/...).
    set +e
    IS_WINDOWS=$(which cmd.exe)
    set -e
    if [[ -z "$IS_WINDOWS" ]]; then
        check_dependency_docker

        ./scripts/env-vars-check

        # Some settings are used to connect to an external dependency,
        # e.g. Azure IoT Hub and IoT Hub Manager API.
        # Depending on which settings and which dependencies are needed,
        # edit the list of variables.
        docker run -it \
            -p 9004:9004 \
            -e PCS_KEYVAULT_NAME \
            -e PCS_AAD_APPID \
            -e PCS_AAD_APPSECRET \
            -v "$PCS_CACHE/sandbox/.config:/root/.config" \
            -v "$PCS_CACHE/sandbox/.dotnet:/root/.dotnet" \
            -v "$PCS_CACHE/sandbox/.nuget:/root/.nuget" \
            -v "$APP_HOME:/opt/code" \
            azureiotpcs/code-builder-dotnet:1.0-dotnetcore /opt/code/scripts/run
    else
        # Note 'winpty' is required to provide a TTY to Docker
        echo "Launching cmd.exe /c winpty ..."
        cmd.exe /c "winpty .\scripts\run.cmd --in-sandbox"
    fi
}

if [[ "$1" == "--help" || "$1" == "-h" ]]; then
    help && set +e && exit 0
fi

if [[ "$1" == "--in-sandbox" || "$1" == "-s" ]]; then
    run_in_sandbox
else
    run
fi

set +e
